from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from rest_framework import status
import logging
from rest_framework_jwt.settings import api_settings

from .models import OAuthQQUser
from .utils import generate_save_user_token
from .serializers import QQAuthUserSerializer
from carts.utils import merge_cart_cookie_to_redis


logger = logging.getLogger('django')


# Create your views here.
# url(r'^qq/user/$', views.QQAuthUserView.as_view()),
class QQAuthUserView(APIView):

    def get(self, request):
        """完成oauth 2.0认证"""
        # 提取code请求参数
        code = request.query_params.get('code')
        if not code:
            return Response({'message': '没有code'}, status=status.HTTP_400_BAD_REQUEST)
        # 创建OAuthQQ的工具对象
        oauthqq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                          client_secret=settings.QQ_CLIENT_SECRET,
                          redirect_uri=settings.QQ_REDIRECT_URI)
        try:
            # 使用code向QQ服务器请求access_token
            access_token = oauthqq.get_access_token(code)
            # 使用access_token向QQ服务器请求openid
            openid = oauthqq.get_open_id(access_token)
        except Exception as error:
            logger.info(error)
            return Response({'message': 'QQ服务异常'}, status=status.HTTP_503_SERVICE_UNAVAILABLE)

        try:
            # 使用openid查询该QQ用户是否在美多商城中绑定过用户
            oauth_model = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:  # 如果数据库中取不到openid,肯定是没有绑定过用户
            # 如果openid没绑定美多商城用户，创建用户并绑定到openid
            # 对openid进行加密之后再响应给前端
            access_token_openid = generate_save_user_token(openid)

            return Response({'access_token': access_token_openid})
        else:

            # 如果openid已绑定美多商城用户，直接生成JWT token，并返回
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER  # 加载jwt配置中的处理payload的函数
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER  # 加载生成token的函数

            # 获取oauthModel关联/绑定的用户模型对象
            user = oauth_model.user
            payload = jwt_payload_handler(user)  # 传入用户对象来生成payload
            token = jwt_encode_handler(payload)

            response = Response({
                'user_id': user.id,
                'username': user.username,
                'token': token
            })
            # 要做购物车合并
            return merge_cart_cookie_to_redis(request, user, response)

    def post(self, request):
        """openid绑定用户"""
        # 1.创建序列化器对象
        serializer = QQAuthUserSerializer(data=request.data)
        # 2.数据校验
        serializer.is_valid(raise_exception=True)
        # 3.保存
        user = serializer.save()

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER  # 加载jwt配置中的处理payload的函数
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER  # 加载生成token的函数

        payload = jwt_payload_handler(user)  # 传入用户对象来生成payload
        token = jwt_encode_handler(payload)


        response = Response({
            'user_id': user.id,
            'username': user.username,
            'token': token
        })
        # 要做购物车合并
        return merge_cart_cookie_to_redis(request, user, response)


class QQAuthURLView(APIView):

    def get(self, request):
        """返回QQ扫码url"""
        # 获取next参数的来源
        next = request.query_params.get('next')
        if not next:
            next = '/'

        # # QQ登录参数
        # QQ_CLIENT_ID = '101514053'
        # QQ_CLIENT_SECRET = '1075e75648566262ea35afa688073012'
        # QQ_REDIRECT_URI = 'http://www.meiduo.site:8080/oauth_callback.html'
        # 创建OAuthQQ的工具对象
        oauthqq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                          client_secret=settings.QQ_CLIENT_SECRET,
                          redirect_uri=settings.QQ_REDIRECT_URI,
                          state=next)

        # 调用SDK中的方法获取到拼接好的扫码url
        login_url = oauthqq.get_qq_url()

        # 响应出来
        return Response({'login_url': login_url})
